/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Web_Helper;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;
import javax.faces.context.FacesContext;



/**
 *
 * @author Randall Chia
 */
public class Helper_PaymentValidator {
    
    
    /*
     * Validate payment. This method should be called by the JSF bean handling the payment once the user
     * has finished his payment and has been redirected to the return URL. Upon returning to that page
     * the JSF bean will call this method to perform a PDT operation to paypal through a HTTP POST request
     * and paypal will reply with a message. If the message begins with SUCCESS, then the payment is validated
     * else the message will begin with FAIL.
    
    */
    public static boolean validatePayment() throws IOException{
        
        String returnString = "NO VALUE";
        
        
        //Get the Transaction ID
        Map requestMap = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
        String transactionID = "no id found";
          
        if(requestMap.containsKey("tx")) {
            transactionID = (String) requestMap.get("tx");
        }else{
            System.out.println("ATTEMPT TO VALIDATE A PAYMENT FAILED, COULD NOT FIND TRANSACTION ID IN URL");
            return false;
        }
        
        System.out.println("PaymentConfirmManagedBean retrieved transaction ID " + transactionID);
        
        //***************
        //TODO CODE, check if this ID has been validated before. We do not want the same ID
        //to be validated multiple times as it will throw a SUCCESS response each time and create
        //a transaction entity with each time it is used.
        //***************
        System.out.println("PaymentConfirmManagedBean trying to validate PDT...");
        
        //Prepare the form's name-value pairs
        String name1 = "cmd=";
        String value1 = "_notify-synch";
        String value1_Encode = URLEncoder.encode(value1, "UTF-8");
        
        String name2 = "tx=";
        String value2 = transactionID;
        String value2_Encode = URLEncoder.encode(value2, "UTF-8"); 
        
        String name3 = "at=";
        String value3 = "6RFkn5WXerdKTc0XFWA6na-f9Brsz9kQb7sNm5y2vUGort1IApRbq5swgAW"; //this is the ID token of the seller
        String value3_Encode = URLEncoder.encode(value3, "UTF-8"); 
     
        //Create the URL
        URL paypalURL = new URL("https://www.sandbox.paypal.com/cgi-bin/webscr");      

        
        //Create the URLConnection and set ti to do output and input
        HttpURLConnection connection = (HttpURLConnection) paypalURL.openConnection();    
        connection.setDoOutput(true);
        connection.setDoInput(true);
        
        connection.setRequestMethod("POST");
        
        String content = name1 + value1_Encode + "&" + name2 + value2_Encode + "&" + name3 + value3_Encode;
        
        //System.out.println(content+"\n\n");
        
        //Create the data output Stream, write and close
        DataOutputStream outStream = new DataOutputStream(connection.getOutputStream());
        outStream.writeBytes(content);
        outStream.flush();
        outStream.close();
        
        //----------------------------------------------------------
        
        //Create the buffer reader and start reading line by line
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String lineString = "";
        
        while((lineString=in.readLine())!=null) {
            if(lineString.equals("SUCCESS")) returnString="SUCCESS"; 
            System.out.println(lineString);
        }
        in.close();
        //End validation
        
        
        
        
        System.out.println("Validation of payment ID: " + transactionID + "  "+ returnString);
        if(returnString.equals("SUCCESS")) return true; else return false;
        
    
    }
    
}
